package main.动态规划;

/**
 * @author tmh
 * @date 2024/9/4 21:05
 * @description
 */
public class T5最长回文子串 {
    //dp[i][j] 表示s[i->j]是否是字符串
    public String longestPalindrome(String s) {
        int len = s.length();
        //特殊值判断
        if (len < 2) {
            return s;
        }
        boolean[][] dp = new boolean[len][len];
        for (int i = 0; i < len; i++) {
            dp[i][i] = true;
        }
        char[] charArray = s.toCharArray();

        int manLen = 1;
        int begin = 0;
        for (int j = 1; j < s.length(); j++) {
            for (int i = 0; i < s.length(); i++) {
                //如果两个字符不相同
                if (charArray[i] != charArray[j]) {
                    dp[i][j] = false;
                } else {
                    //公式背诵
                    if (j - i < 3) {
                        dp[i][j] = true;
                    } else {
                        dp[i][j] = dp[i + 1][j - 1];
                    }
                }

                //更新maxLen和begin
                if (dp[i][j] && j - i + 1 > manLen) {
                    manLen = j - i + 1;
                    begin=i;
                }
            }
        }
        return s.substring(begin,begin+manLen);
    }
}
